package com.example.springbootdemo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@RestController
public class EmailSendAction {

    @Resource
    JavaMailSender mailSender;

    @Value("${myEmail}")
    String myEail;

    @GetMapping("sendCode1")
    public String sendForgetCode(String email, HttpSession session){
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom(myEail);
        smm.setTo(email);
        smm.setSubject("找回密码");
        String code = System.currentTimeMillis() + "";
        //截取后4位
        code = code.substring(code.length() - 4);
        //存入会话
        session.setAttribute("forgetCode", code);
        smm.setText("找回密码的验证码是:" + code);
        mailSender.send(smm);
        return "邮件发送成功";
    }


    /**
     * 发送重置密码的链接地址,该地址只能访问一次
     * 1.生成一个随机码(不能重复) => 保存到容器中
     * 2.发送邮件,邮件中包含链接,把该随机码写入 链接参数
     * 3.用户点击链接,从容器中移除随机码，跳转界面
     */

    Set<Object> codeSet = new HashSet<>();

    @RequestMapping("sendCode2")
    public String sendForgetCode2(String email) throws MessagingException {
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        codeSet.add(code);
        //创建Mime类型的消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(myEail);
        helper.setTo(email);
        helper.setSubject("忘记密码");
        helper.setText("<div>请点击链接:<a href='http://127.0.0.1:8080/reset.do?code=" +code +"'>重置密码</a></div>",true);
        mailSender.send(mimeMessage);
        return "重置密码邮箱发送OK";
    }

    @RequestMapping("reset.do")
    public ModelAndView reset(String code,ModelAndView mav){
        if (codeSet.contains(code) == false){
            mav.addObject("msg","没有授权码!");
            mav.setViewName("result");
        }else {
            codeSet.remove(code);
            mav.setViewName("reset");
        }
        return mav;
    }
}
